<template>
  <div>

    <van-overlay :show="overlayVisable" z-index="2">
      <div class="wrapper">
        <van-loading size="24px">
          <span id="loading">数据加载中...</span>
        </van-loading>
      </div>
    </van-overlay>
    <div class="goods-wrap">
      <div class="goods">
        <div class="menu-wrapper" ref="menuWrapper">
          <ul>
            <li class="menu-item" v-for="(good, index) in goodList" :key="index"
              :class="{ current: currentIndex === index }" @click="clickMenu(index)">
              <van-badge v-if="good.num != 0" :content="good.num" position="top-left" style=" font-size: 1px;">

              </van-badge>
              <span class="text bottom-border-1px">
                <img class="icon" v-if="good.icon" :src="good.icon">
                {{ good.name }}
              </span>

            </li>
          </ul>
        </div>
        <div class="foods-wrapper" ref="foodsWrapper">
          <ul>
            <li class="food-list food-list-hook" v-for="(good, index) in goodList" :key="index">
              <h1 class="title">{{ good.name }}</h1>
              <ul>
                <li class="food-item bottom-border-1px" v-for="(food, index) in good.foodList" :key="index">
                  <div class="icon" @click="handleFoodClick(food)">
                    <img width="57" height="57" :src="food.icon">
                  </div>
                  <div class="content">
                    <h2 class="name" @click="handleFoodClick(food)">{{ food.name }}</h2>
                    <p class="desc" @click="handleFoodClick(food)">{{ food.description }}</p>
                    <div class="extra">
                      <span class="count">月售{{ food.sellCount }}份</span>
                      <span>好评率{{ food.rating }}%</span>
                    </div>
                    <div class="price">
                      <span class="now">￥{{ food.price }}</span>
                      <span class="old" v-if="food.oldPrice">￥{{ food.oldPrice }}</span>
                    </div>
                    <div class="cartcontrol-wrapper">
                      <van-stepper v-model="food.num" :show-minus="food.num != 0" :show-input="food.num != 0"
                        :default-value="0" theme="round" :min="0" button-size="22" disable-input
                        @plus="plusShopCart1(food)" @minus="minusShopCart1(food)" />
                    </div>
                  </div>
                </li>
              </ul>
            </li>
          </ul>
        </div>
      </div>
      <Food :food="currentFood" v-if="isShowFoodCard" @close="handleFoodClose">
      </Food>
      
    </div>


    <!-- 购物车 -->
    <div style="position: fixed;bottom: 0;width: 100%;">
      
      <ShopCart @showFoodInfo="showFoodInfo" @handlePayment="handlePayment"
        :cartData="{ shopName: info.shopName, shopCart: shopCart }" />
    </div>

    <!-- 展示购物车 -->
    <van-action-sheet v-model="shopCartVisible" title="购物车">

      <div class="content" style="padding: 16px 16px 10px;overflow: hidden;">
        <div style="background-color: white;width: 100%;height: 350px;overflow:scroll;">
          <van-card v-for="(food, index) in shopCart" :key="index" :thumb="food.icon">
            <template #title>
              <span style="font-weight: 700;font-size: 14px;"> {{ food.name }}</span>
            </template>
            <template #desc>
              <div style="height: 10px;"></div>
              <div style="color: gray;">
                <p>{{ food.description }}</p>
                <div style="height: 5px;"></div>
                <span>月售{{ food.sellCount }}份</span>
                <span style="margin-left: 5%;">好评率{{ food.rating }}%</span>
              </div>
            </template>
            <template #price>
              <span style="color: red;"> ¥{{ food.price * food.num }}</span>
            </template>
            <template #num>
              <van-stepper v-model="food.num" theme="round" :min="0" button-size="22" disable-input
                @plus="plusShopCart(food)" @minus="minusShopCart(food)" />
            </template>
          </van-card>
        </div>

        <div style="position: relative;margin-top: 10px;">
          <!-- 购物车 -->
          <ShopCart @showFoodInfo="showFoodInfo" @handlePayment="handlePayment"
            :cartData="{ shopName: info.shopName, shopCart: shopCart }" />
        </div>
      </div>
    </van-action-sheet>
  </div>

</template>

<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import BScroll from 'better-scroll'
import ShopCart from '../../../components/ShopCart/ShopCart.vue'
import Food from '../../../components/Food/Food.vue'
export default {
  components: {
    ShopCart,
    Food
  },
  data() {
    return {
      scrollY: 0, //右侧滑动的y坐标
      tops: [], // 所有右侧分类li标签的top所组成数组
      food: {},
      shopCartVisible: false, // 是否显示购物车详情
      overlayVisable: false, //  是否显示遮罩
      currentFood: {},
      isShowFoodCard: false,// 是否显示食物的卡片信息
      shopCart: [],
      // customerInfo: {
      //   username: sessionStorage.getItem('username'), //顾客的用户名
      // },
      shopName: sessionStorage.getItem('shopName') ? sessionStorage.getItem('shopName') : '',
    }
  },
  mounted() {
    this.overlayVisable = true
    this.$store.dispatch('shopInfo/getShopInfo')
    this.getcustomerInfo();

    setTimeout(() => {
      this.shopCart = sessionStorage.getItem(this.shopName + this.customerInfo.username + "shopCart") ? JSON.parse(sessionStorage.getItem(this.shopName + this.customerInfo.username + "shopCart")) : []
      //  console.log(this.shopCart);
      this.shopCart.push();
      this.$store.dispatch('good/getGoodList', () => {
        // 从后台获取的数据已更新到状态中, 但界面还没有更新(界面的更新是异步的)
        // 在状态更新之后执行
        this.$nextTick(() => { // 回调函数在界面更新之后立即执行
          // console.log("我被执行了！")
          this._initScroll()
          this._initTops()
          this.overlayVisable = false
        })
      }
      )
    }, 500)

  },
  computed: {
    ...mapState('good', ['goodList']),
    ...mapState("shopInfo", ['info']),
    ...mapState('customer', ['customerInfo']),

    currentIndex() {
      const { tops, scrollY } = this
      //  console.log('currentIndex', scrollY)
      return tops.findIndex((top, index) => {
        return scrollY >= top && scrollY < tops[index + 1]
      })
    },
  },
  methods: {
    ...mapMutations('good', ['UPDATE_GOODLIST']),
    ...mapActions('customer', ['getcustomerInfo']),
    /**
     * 从商品界面点加号
     * @param {} food 
     */
    plusShopCart1(food) {

      setTimeout(() => {
        var newfood = JSON.parse(JSON.stringify(food))
        let flag = 0
        for (var i = 0; i < this.shopCart.length; i++) {
          if (this.shopCart[i].foodId == newfood.foodId) {
            flag = 1;
            this.shopCart[i].num = newfood.num;
            break;
          }
        }
        if (flag == 0) this.shopCart.push(newfood);
        newfood.type = 1 // 1是加
        this.UPDATE_GOODLIST(newfood)
        this.addToSessionStorage()
      }, 10)

    },

    /**
   *从购物车点击加号
   * @param {} food 
   */
    plusShopCart(food) {

      for (var i = 0; i < this.goodList.length; i++) {
        var sign = 0;
        for (var j = 0; j < this.goodList[i].foodList.length; j++) {
          var item = this.goodList[i].foodList[j];
          if (item.foodId == food.foodId) {
            console.log(item)
            item.num++;
            sign = 1;
            break;
          }
          if (sign == 1) break;
        }
      }

      setTimeout(() => {
        var newfood = JSON.parse(JSON.stringify(food))
        let flag = 0
        for (var i = 0; i < this.shopCart.length; i++) {
          if (this.shopCart[i].foodId == newfood.foodId) {
            flag = 1;
            this.shopCart[i].num = newfood.num;
            break;
          }
        }
        if (flag == 0) this.shopCart.push(newfood);
        newfood.type = 1 // 1是加
        this.UPDATE_GOODLIST(newfood)
        this.addToSessionStorage()
      }, 10)

    },

    /**
     * 从商品界面点减号
     * @param {} food 
     */
    minusShopCart1(food) {

      setTimeout(() => {
        var newfood = JSON.parse(JSON.stringify(food))
        for (var i = 0; i < this.shopCart.length; i++) {
          if (this.shopCart[i].foodId == newfood.foodId) {
            this.shopCart[i] = newfood;
            break;
          }
        }
        this.shopCart = this.shopCart.filter(item => item.num > 0)
        newfood.type = 2 // 2 是减
        this.UPDATE_GOODLIST(newfood)
        this.addToSessionStorage()
      }, 10)

    },


    /**
     * 从购物车点击减号
     * @param {} food 
     */
    minusShopCart(food) {

      for (var i = 0; i < this.goodList.length; i++) {
        var sign = 0;
        for (var j = 0; j < this.goodList[i].foodList.length; j++) {
          var item = this.goodList[i].foodList[j];
          if (item.foodId == food.foodId) {
            //   console.log(item)
            item.num--;
            sign = 1;
            break;
          }
          if (sign == 1) break;
        }
      }


      setTimeout(() => {
        var newfood = JSON.parse(JSON.stringify(food))
        for (var i = 0; i < this.shopCart.length; i++) {
          if (this.shopCart[i].foodId == newfood.foodId) {
            this.shopCart[i] = newfood;
            break;
          }
        }
        this.shopCart = this.shopCart.filter(item => item.num > 0)
        newfood.type = 2 // 2 是减
        this.UPDATE_GOODLIST(newfood)
        this.addToSessionStorage()
      }, 10)
    },

    /**
     * 存到session当中
     */
    addToSessionStorage() {
      sessionStorage.setItem(this.shopName + this.customerInfo.username + "goodList", JSON.stringify(this.goodList));
      sessionStorage.setItem(this.shopName + this.customerInfo.username + "shopCart", JSON.stringify(this.shopCart));
    },

    showFoodInfo() {
      this.shopCartVisible = !this.shopCartVisible
    },


    // 跳转创建确认订单页面
    handlePayment(totalMoney) {
      var order = {};
      var foodList = [];
      var num = 0;
      // console.log(this.shopCart)
      for (var item of this.shopCart) {
        foodList.push({
          id: '',
          foodId: item.foodId, //商品id
          icon: item.icon,// 商品图片
          oldPrice: item.oldPrice.toFixed(2),//商品原价
          name: item.name, // 商品名称
          num: item.num, // 商品数量
          description: item.description,//商品描述
          price: item.price, // 商品单价
          foodorderId: '', //订单id 后端生成
        })
        num += item.num
      }

      order.id = ''; // 订单id
      order.num = num; // 订单总数
      order.shopName = this.info.name; //商家名称
      order.foodList = foodList; // 订单食物列表
      order.createBy = this.info.createBy;// 绑定商家的用户名
      order.shopId = this.info.id; // 订单商家id
      order.totalMoney = totalMoney.toFixed(2); // 订单总价
      order.createTime = this.getCurretnTime(); // 下单时间
      order.remainingTime = 15 * 60 * 1000; // 设置剩余支付时间
      order.status = 2; //未支付
      order.payType = '余额支付';// 设置默认余额支付
      sessionStorage.setItem(this.customerInfo.username + "order", JSON.stringify(order));
      this.$router.push({
        name: 'OrderConfirm'
      });
    },

    /**
        * 获取当前时间
        */
    getCurretnTime() {
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth() + 1;
      mm = mm.toString().padStart(2, 0);
      let dd = new Date().getDate().toString().padStart(2, 0);
      let hh = new Date().getHours().toString().padStart(2, 0);
      let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes();
      let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds();
      return yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss
    },

    // 处理食物的点击事件
    handleFoodClick(food) {
      this.currentFood = food
      this.isShowFoodCard = !this.isShowFoodCard
    },
    // 是否关闭食物卡片
    handleFoodClose(isClose) {
      this.isShowFoodCard = !isClose
    },
    _initScroll() {
      // 控制左侧列表滑动的scroll
      new BScroll(this.$refs.menuWrapper, {
        click: true  // 分发点击事件
      })

      // 控制右侧列表滑动的scroll
      this.foodsScroll = new BScroll(this.$refs.foodsWrapper, {
        // startY: -100
        probeType: 1, //会在滑动(手指触摸)过程中实时派发scroll事件
        click: true
      })

      // 监视右侧列表的滚动
      this.foodsScroll.on('scroll', (event) => {
        // 获取滚动的y坐标
        //  console.log('scroll', event.y)
        this.scrollY = Math.abs(event.y)
      })

      // 监视右侧列表的滚动结束
      this.foodsScroll.on('scrollEnd', (event) => {
        // 获取滚动的y坐标
        //  console.log('scrollEnd', event.y)
        this.scrollY = Math.abs(event.y)
      })
    },

    _initTops() {
      // 找到所有li
      const lis = this.$refs.foodsWrapper.getElementsByClassName('food-list-hook')
      // 统计top
      const tops = []
      let top = 0
      tops.push(top)
      Array.prototype.slice.call(lis).forEach(li => {
        top += li.clientHeight
        tops.push(top)
      })
      // 更新状态
      this.tops = tops
      //  console.log(tops)
    },

    clickMenu(index) {
      // console.log('clickMenu()')

      // 立即更新scrollY, 立即让currentIndex重新计算
      this.scrollY = this.tops[index]
      // 让右侧列表平滑滚动到指定位置
      this.foodsScroll.scrollTo(0, -this.tops[index], 300)
    },

    showFood(food) {
      // 更新food
      this.food = food
      // 显示food组件
      this.$refs.food.toggleShow()
    },

  },
}
</script>

<style lang="stylus" rel="stylesheet/stylus">
  @import "../../../common/stylus/mixins.styl"
  .wrapper
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
  .van-action-sheet__header
      background-color: #fff100;
      color:gray;
  .van-stepper--round
    .van-stepper__plus
     background-color: rgba(255, 170, 0, 0.986);
  .goods
    display: flex
    position: absolute
    top: 220px
    bottom: 46px
    width: 100%
    background: #fff;
    overflow: hidden
    .menu-wrapper
      flex: 0 0 80px
      width: 80px
      background: #f3f5f7
      .menu-item
        display: table
        height: 54px
        width: 56px
        padding: 0 12px
        line-height: 14px
        &.current
          position: relative
          z-index: 10
          margin-top: -1px
          background: #fff
          color: $yellow
          font-weight: 700
          .text
            border-none()
        .icon
          display: inline-block
          vertical-align: top
          width: 12px
          height: 12px
          margin-right: 2px
          background-size: 12px 12px
          background-repeat: no-repeat
        .text
          display: table-cell
          width: 56px
          vertical-align: middle
          bottom-border-1px(rgba(7, 17, 27, 0.1))
          font-size: 12px
    .foods-wrapper
      flex: 1
      .title
        padding-left: 14px
        height: 26px
        line-height: 26px
        border-left: 2px solid #d9dde1
        font-size: 12px
        color: rgb(147, 153, 159)
        background: #f3f5f7
      .food-item
        display: flex
        margin: 18px
        padding-bottom: 18px
        bottom-border-1px(rgba(7, 17, 27, 0.1))
        &:last-child
          border-none()
          margin-bottom: 0
        .icon
          flex: 0 0 57px
          margin-right: 10px
        .content
          flex: 1
          .name
            margin: 2px 0 8px 0
            height: 14px
            line-height: 14px
            font-size: 14px
            color: rgb(7, 17, 27)
          .desc, .extra
            line-height: 10px
            font-size: 10px
            color: rgb(147, 153, 159)
          .desc
            line-height: 12px
            margin-bottom: 8px
          .extra
            .count
              margin-right: 12px
          .price
            font-weight: 700
            line-height: 24px
            .now
              margin-right: 8px
              font-size: 14px
              color: rgb(240, 20, 20)
            .old
              text-decoration: line-through
              font-size: 10px
              color: rgb(147, 153, 159)
          .cartcontrol-wrapper
            position: absolute
            right: 0
            bottom: 12px
</style>


